public class Solution1038 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    int last=0;

    public TreeNode bstToGst(TreeNode root) {
        if (root==null){
            return null;
        }
        dfs(root);
        return root;
    }

    private void dfs(TreeNode root) {
        if (root.right!=null){
            dfs(root.right);
        }
        last=last+root.val;
        root.val=last;
        if (root.left!=null){
            dfs(root.left);
        }
    }

    public static void main(String[] args) {
        System.out.println(new Solution1038().bstToGst(new TreeNode(4,new TreeNode(1,new TreeNode(0),new TreeNode(2,null,new TreeNode(3))),new TreeNode(6,new TreeNode(5),new TreeNode(7,null,new TreeNode(8))))).left.left.val);
    }
}
